package com.dianrui.agent.okhttp;

import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.util.Log;


import com.dianrui.agent.util.SharedUtil;
import com.dianrui.agent.util.StringUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class OkHttpRequest {
    private Handler handler;
    private volatile static OkHttpRequest mInstance;
    private OkHttpClient mOkHttpClient;

    public OkHttpRequest(OkHttpClient okHttpClient) {
        handler = new Handler(Looper.getMainLooper());
        if (okHttpClient == null) {
            mOkHttpClient = new OkHttpClient();
        } else {
            mOkHttpClient = okHttpClient;
        }
    }


    /**
     * 单例模式
     */
    //获取单利
    public static OkHttpRequest getInstance() {

        return initClient(null);

    }

    public static OkHttpRequest initClient(OkHttpClient okHttpClient) {
        if (mInstance == null) {
            synchronized (OkHttpRequest.class) {
                if (mInstance == null) {
                    mInstance = new OkHttpRequest(okHttpClient);
                }
            }
        }
        return mInstance;
    }

    public void getRequests(final String url,  final XCallBack callback) {
        Request request = new Request.Builder().url(url).get().build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e("TAG", "请求失败=" + e.getMessage());
                onFailedResponse(e.getMessage(), callback);
                call.cancel();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response!=null && response.isSuccessful()) {
                    ResponseBody responseBody = response.body();
                    String date = responseBody.string();
                    onSuccessResponse(date, callback);
                    Log.e("服务器返回数据---->", "====================================网络请求[" + "],请求日志如下===================================" +
                            "\n\n请求地址:" + url +
                            "\n\n请求数据响应代码:" + response.code() +
                            "\n\n服务器返回的数据>" + date);
                }else {
                    ResponseBody responseBody = response.body();
                    String date = responseBody.string();
                    Log.e("服务器返回数据---->", "====================================网络请求[" + "],请求日志如下===================================" +
                            "\n\n请求地址:" + url +
                            "\n\n请求数据响应代码:" + response.code() +
                            "\n\n服务器返回的数据>" + date);
                    onFailedResponse(call.toString(), callback);
                    call.cancel();
                }
            }
        });

    }

    public void postRequests(final String url, final String requestparams, final XCallBack callback) {
        OkHttpUtils.postString().url(url).tag(this).content(requestparams).mediaType(MediaType.parse("application/json; charset=utf-8")).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("TAG", "请求失败=" + e.getMessage());
                onFailedResponse(e.getMessage(), callback);
                call.cancel();
            }

            @Override
            public void onResponse(String response, int id) {
                if (!StringUtils.isEmpty(response)) {
                    onSuccessResponse(response, callback);
                    Log.e("服务器返回数据---->", "====================================网络请求[" + "],请求日志如下===================================" +
                            "\n\n传给服务器地址:" + url +
                            "\n\n传给服务器的参数:" + requestparams +
                            "\n\n服务器返回的数据>" + response);
                }else {
                    Log.e("服务器返回数据---->", "====================================网络请求[" + "],请求日志如下===================================" +
                            "\n\n传给服务器地址:" + url +
                            "\n\n服务器返回的数据>" + response);
                    onFailedResponse(response, callback);
                }
            }
        });
    }

    public void postTokenRequests(final String url, final String requestparams, final XCallBack callback) {
        String token = SharedUtil.getToken();
        String areaid = SharedUtil.getAreaid();
        if (!StringUtils.isEmpty(areaid)) {
            Log.e("token是", token);
            Log.e("areaid是", areaid);
            OkHttpUtils.postString().url(url).tag(this).content(requestparams).addHeader("token", token).addHeader("area", areaid).mediaType(MediaType.parse("application/json; charset=utf-8")).build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    Log.e("TAG", "请求失败=" + e.getMessage());
                    onFailedResponse(call.toString(), callback);
                    call.cancel();
                }

                @Override
                public void onResponse(String response, int id) {
                    if (!StringUtils.isEmpty(response)) {
                        onSuccessResponse(response, callback);
                        Log.e("服务器返回数据---->", "====================================网络请求[" + "],请求日志如下===================================" +
                                "\n\n传给服务器地址:" + url +
                                "\n\n传给服务器的参数:" + requestparams +
                        "\n\n服务器返回的数据>" + response);
                    }else {
                        Log.e("服务器返回数据---->", "====================================网络请求[" + "],请求日志如下===================================" +
                                "\n\n传给服务器地址:" + url +
                                "\n\n服务器返回的数据>" + response);
                        onFailedResponse(response, callback);
                    }
                }
            });
        }else {
            OkHttpUtils.postString().url(url).tag(this).content(requestparams).addHeader("token", token).addHeader("area", "0").mediaType(MediaType.parse("application/json; charset=utf-8")).build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    Log.e("TAG", "请求失败=" + e.getMessage());
                    onFailedResponse(call.toString(), callback);
                    call.cancel();
                }

                @Override
                public void onResponse(String response, int id) {
                    if (!StringUtils.isEmpty(response)) {
                        onSuccessResponse(response, callback);
                        Log.e("服务器返回数据---->", "====================================网络请求[" + "],请求日志如下===================================" +
                                "\n\n传给服务器地址:" + url +
                                "\n\n传给服务器的参数:" + requestparams +
                                "\n\n服务器返回的数据>" + response);
                    }else {
                        Log.e("服务器返回数据---->", "====================================网络请求[" + "],请求日志如下===================================" +
                                "\n\n传给服务器地址:" + url +
                                "\n\n服务器返回的数据>" + response);
                        onFailedResponse(response, callback);
                    }
                }
            });
        }
    }


    public void postLoginTokenRequests(final String url, final String requestparams, final XCallBack callback) {
        String token = SharedUtil.getToken();
        OkHttpUtils.postString().url(url).tag(this).content(requestparams).addHeader("token", token).mediaType(MediaType.parse("application/json; charset=utf-8")).build().execute(new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("TAG", "请求失败=" + e.getMessage());
                onFailedResponse(call.toString(), callback);
                call.cancel();
            }

            @Override
            public void onResponse(String response, int id) {
                if (!StringUtils.isEmpty(response)) {
                    onSuccessResponse(response, callback);
                    Log.e("服务器返回数据---->", "====================================网络请求[" + "],请求日志如下===================================" +
                            "\n\n传给服务器地址:" + url +
                            "\n\n传给服务器的参数:" + requestparams +
                            "\n\n服务器返回的数据>" + response);
                }else {
                    Log.e("服务器返回数据---->", "====================================网络请求[" + "],请求日志如下===================================" +
                            "\n\n传给服务器地址:" + url +
                            "\n\n服务器返回的数据>" + response);
                    onFailedResponse(response, callback);
                }
            }
        });
    }

    private void onSuccessResponse(final String result, final XCallBack callBack) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callBack != null) {
                    callBack.onResponse(result);
                }
            }
        });
    }

    private void onFailedResponse(final String result, final XCallBack callBack) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callBack != null) {
                    callBack.FailedRequest(result);
                }
            }
        });
    }

    public interface XCallBack {
        void onResponse(String result);
        void FailedRequest(String result);
    }
}
